use crate::models::order_return_payments::{self, CreateOrderReturnPaymentParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/order-return-payments", post(create))
        .route("/order-return-payments/:id", get(get_by_id))
        .route("/order-return-payments/:id/delete", post(delete))
        .route(
            "/order-return-payments/by-order-return/:order_return_id",
            get(get_by_order_return),
        )
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateOrderReturnPaymentParams>,
) -> Result<Response> {
    let order_return_payment = order_return_payments::Model::create(&state.db, &params).await?;
    format::json(order_return_payment)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let order_return_payment = order_return_payments::Model::find_by_id(&state.db, &id).await?;
    format::json(order_return_payment)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): Path<String>,
) -> Result<Response> {
    let order_return_payment = order_return_payments::Model::find_by_id(&state.db, &id).await?;
    order_return_payment.delete(&state.db).await?;
    format::json(())
}

async fn get_by_order_return(
    State(state): State<AppContext>,
    axum::extract::Path(order_return_id): axum::extract::Path<String>,
) -> Result<Response> {
    let order_return_payments =
        order_return_payments::Model::find_by_order_return_id(&state.db, &order_return_id).await?;
    format::json(order_return_payments)
}
